package com.peanut.baby.mvp.profile;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.peanut.baby.AppConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.model.PTag;
import com.peanut.baby.model.User;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.follow.FollowFansActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.mycontent.CourseFragment;
import com.peanut.baby.mvp.mycontent.QaFragment;
import com.peanut.baby.mvp.profile.comments.ProfileReplysFragment;
import com.peanut.baby.mvp.profile.moments.ProfileMomentsFragment;
import com.peanut.baby.util.ColorUtils;
import com.peanut.baby.widget.TitleTabRadioButton;
import com.peanut.devlibrary.adapter.FragmentTabAdapter;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by anonymouslystudio on 2017/8/2.
 */

public class ProfileActivity extends BaseMvpActivity implements RadioGroup.OnCheckedChangeListener,
        ViewPager.OnPageChangeListener,
        ProfileContract.View,
        TitleLayout.OnTitleClickListener,
        View.OnClickListener{
    ArrayList<Fragment> fragments;
    FragmentTabAdapter adapter;

    @BindView(R.id.profile_radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.profile_viewpager)
    ViewPager viewpager;
    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.profile_avatar)
    CircleImageView avatar;
    @BindView(R.id.profile_nick)
    TextView nick;
    @BindView(R.id.profile_tags)
    TextView tags;
    @BindView(R.id.profile_following)
    TextView following;
    @BindView(R.id.profile_fans)
    TextView fans;
    @BindView(R.id.profile_radio_bbs)
    TitleTabRadioButton radioBbs;
    @BindView(R.id.profile_radio_reply)
    TitleTabRadioButton radioReply;
    @BindView(R.id.profile_radio_course)
    TitleTabRadioButton radioCourse;
    @BindView(R.id.profile_radio_qas)
    TitleTabRadioButton radioQa;
    @BindView(R.id.profile_follow)
    CheckBox follow;

    private String userId = "";
    private User user;
    private ProfilePresenter presenter;

    public static void start(Context ctx, String userId) {
        ctx.startActivity(new Intent(ctx, ProfileActivity.class).putExtra("userId", userId));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != RESULT_OK){
            return;
        }

        if(requestCode == AppConfig.RequestResult.REQUEST_CODE_LOGIN
                || requestCode == AppConfig.RequestResult.REQUEST_CODE_BIND){
            presenter.getUserInfo(userId);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        ButterKnife.bind(this);
        userId = getIntent().getStringExtra("userId");
        if (StringUtil.isNullOrEmpty(userId)) {
            showToast("缺少用户Id");
            finish();
            return;
        }
        Log.d("profileActivity","userId "+userId);
        presenter = new ProfilePresenter(this,this);
        initView();
    }

    private void initView() {
        title.setTitle("用户信息");
        title.setOnTitleClickedListener(this);

        viewpager.setOnPageChangeListener(this);
        radioGroup.setOnCheckedChangeListener(this);
        follow.setOnClickListener(this);
        following.setOnClickListener(this);
        fans.setOnClickListener(this);

        fragments = new ArrayList<>();
        fragments.add(ProfileMomentsFragment.newInstance(userId));
        fragments.add(ProfileReplysFragment.newInstance(userId));
        fragments.add(CourseFragment.newInstance(userId));
        fragments.add(QaFragment.newInstance(userId));

        adapter = new FragmentTabAdapter(getSupportFragmentManager(), fragments);
        viewpager.setAdapter(adapter);

        presenter.getUserInfo(userId);
//        presenter.getTags(userId);

    }

    private void bindUserInfoViews() {
        if (user != null) {
            ImageLoader.getInstance().loadImageView(ProfileActivity.this, user.avatar, avatar);
            nick.setText(user.nickname);
            following.setText("关注 " + user.concernCount);
            fans.setText("粉丝 " + user.fansCount);
            radioBbs.setText("Ta的内容\n(" + user.postCount + ")");
            radioReply.setText("Ta的回复\n(" + user.replyCount + ")");
            radioCourse.setText("Ta的课程\n(" + user.liveCount + ")");
            radioQa.setText("Ta的问答\n(" + user.answerCount + ")");
            follow.setChecked(user.isConcerned == 1);
            follow.setText(user.isConcerned == 1? "已关注":"关注");
            if(InitManager.getInstance().getUserId().equals(userId)){
                follow.setVisibility(View.GONE);
            }else{
                follow.setVisibility(View.VISIBLE);
            }

        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        setCurrent(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.profile_radio_bbs:
                setCurrent(0);
                break;
            case R.id.profile_radio_reply:
                setCurrent(1);
                break;
            case R.id.profile_radio_course:
                setCurrent(2);
                break;
            case R.id.profile_radio_qas:
                setCurrent(3);
                break;

        }
    }

    private void setCurrent(int currentIndex) {

        RadioButton radioButton = (RadioButton) radioGroup.getChildAt(currentIndex);
        if (!radioButton.isChecked()) {
            radioButton.setChecked(true);
        }

        if (viewpager.getCurrentItem() != currentIndex) {
            viewpager.setCurrentItem(currentIndex);
        }

    }

    @Override
    public void onGetUserInfo(User user) {
        this.user = user;
        bindUserInfoViews();
    }

    @Override
    public void onGetUserInfoFailed(String reason) {
        showToast("获取用户信息失败 " + reason);
        finish();
    }

    @Override
    public void onChangeStatusSuccess(int isConcern) {
        dismissProgressDialog();
        user.isConcerned = isConcern;
        bindUserInfoViews();
    }

    @Override
    public void onChangeStatusFailed(String reason) {
        dismissProgressDialog();
        showToast(reason);
        bindUserInfoViews();
    }

    @Override
    public void onSubscribedTagsGet(boolean success, List<PTag> _tags, String failReason) {
        if(success && _tags != null && !_tags.isEmpty()){
            tags.setVisibility(View.VISIBLE);
            tags.setText(getTagsDisplaySpannable(_tags));
        }else{
            tags.setVisibility(View.GONE);
        }
    }

    private SpannableStringBuilder getTagsDisplaySpannable(List<PTag> tags){
        int len = tags.size();
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<len;i++){
            sb.append(tags.get(i).name);
            sb.append(" ");
        }
        String orgStr = sb.toString();
        SpannableStringBuilder builder = new SpannableStringBuilder(orgStr);
        for(int i=0;i<len;i++){
            PTag tag = tags.get(i);
            int index = orgStr.indexOf(tag.name);
            int end = index + tag.name.length();
            BackgroundColorSpan bgSpan = new BackgroundColorSpan(ColorUtils.getRandomTagBgColor());
            builder.setSpan(bgSpan,index,end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            ForegroundColorSpan bgSpan2 = new ForegroundColorSpan(Color.WHITE);
            builder.setSpan(bgSpan2,index,end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        return builder;
    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {

    }

    @Override
    public void onTitleClicked() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.profile_follow:
            case R.id.profile_following:
            case R.id.profile_fans:
                if(InitManager.getInstance().getUser() == null){
                    LoginActivity.startForResult(ProfileActivity.this);
                    bindUserInfoViews();
                    return;
                }
                if(StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)){
                    BindMobileActivity.startForResult(ProfileActivity.this);
                    bindUserInfoViews();
                    return;
                }
                if(v.getId() == R.id.profile_follow){
                    showProgressDialog("请稍候...",false);
                    presenter.changeFollowStatus(userId);
                }else if(v.getId() == R.id.profile_following){
                    FollowFansActivity.start(this,true,userId);
                }else if(v.getId() == R.id.profile_fans){
                    FollowFansActivity.start(this,false,userId);
                }

                break;
        }
    }
}
